//
//  HETWChatManage.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/25.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HETWChatManage.h"
#import "HEDocImMsgModel.h"
#import "HEIMForward.h"
#import "HEAudioRecordManage.h"
#import "HEIMVideoObject.h"
#import "HETWInfoEntity.h"

@interface HETWChatManage ()<HESocketManagerDelegate>

@property (nonatomic, strong) NSMutableArray *cacheIMDataList;

@property (nonatomic, strong) NSMutableArray <HEIMMessageModel *>*modelList;

@property (nonatomic, strong) NSOperationQueue *queue;

@property (nonatomic, strong) dispatch_semaphore_t semaphore;

@end

@implementation HETWChatManage

#pragma mark - LifeCycle
+(instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static HETWChatManage *instance;
    dispatch_once(&onceToken, ^{
        instance = [[HETWChatManage alloc] init];
    });
    return instance;
}

- (instancetype)init {
    if (self = [super init]) {
        self.semaphore = dispatch_semaphore_create(0); //默认创建的信号为0
        self.queue = [[NSOperationQueue alloc] init];
        self.queue.maxConcurrentOperationCount = 1; // 串行队列
        
        [[HESocketManager sharedManager] addDelegate:self];
    }
    return self;
}

- (void)sendMessage:(HEIMMessageModel *)message {
 
    // 加入缓存
    [self cacheIMMassage: message];
    
    // 发送数据
    [self sendQueueIMMassage];
}

/**
 1、缓存发送的原始数据
 2、从缓存中获取 加入发送队列
 */
- (void)cacheIMMassage:(HEIMMessageModel *)message {
 
    HETWInfoEntity *entitiy = [self returnIMEntity: message];
//    HETWInfoEntity *entitiy = [HETWInfoEntity new];

    [self.modelList addObject:message];
    // 数组转字典
    [self.cacheIMDataList addObject: [entitiy mj_keyValues]];

    [self saveIMInfoListWithToId:message.message.to];
}
 
// 保存消息数据
- (void)saveIMInfoListWithToId:(NSString *)to {
    NSString *key = [self getCacheKeyWithToId: to];
    YYCache *cache = [[YYCache alloc] initWithName: key];
    // 存json字符串
    [cache setObject:[self.cacheIMDataList mj_JSONString] forKey: KUserSendIMCache];
}

// 获取缓存的key
- (NSString *)getCacheKeyWithToId:(NSString *)to {
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;

    NSString *aiDataKey = [NSString stringWithFormat:@"%@-%@-%@-%@",KUserSendIMCache,
                           user.id, to, _orgData.inst_id];
    return aiDataKey;
}

- (NSArray <HEIMMessageModel *>*)getIMCacheWithSession:(HEIMSession *)session {
    NSString *key = [self getCacheKeyWithToId: session.sessionId];

    YYCache *cache = [[YYCache alloc] initWithName: key];
    NSString *cacheStr = (NSString *)[cache objectForKey: KUserSendIMCache];
    
    NSArray *cacheArr = [DYTools getContainersObjectFromJsonString:cacheStr];
    if (cacheArr == nil) {
        self.cacheIMDataList = @[].mutableCopy;
    }else {
        self.cacheIMDataList = cacheArr.mutableCopy;
    }

    NSArray *imDataModels = [HEDocImMsgModel mj_objectArrayWithKeyValuesArray: self.cacheIMDataList];
    self.modelList = [HEIMForward transformNoSendTWModel: imDataModels].mutableCopy;
    return self.modelList;
}

- (HETWInfoEntity *)returnIMEntity:(HEIMMessageModel *)message {
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    HEIMMessage *msg = message.message;
    
    HETWInfoEntity *entitiy = [HETWInfoEntity new];
    entitiy.ask_level = 1;
    entitiy.doc_id = _orgData.doc_id;
    entitiy.doc_name = _orgData.doc_name;
    entitiy.status = 1;
    entitiy.is_read = 0;
    entitiy.inst_id = _orgData.inst_id;
    entitiy.usid = user.id;

    switch (message.message.type) {
        case HEIMMessageTypeText:
        {
            HETWIMInfoModel *content = [HETWIMInfoModel new];
            content.content = msg.text;
            content.type = TWIM_TEXT;
            entitiy.user_ask = [content mj_JSONString];
            return entitiy;
        }
            break;
        case HEIMMessageTypeAudio:
        {
            HEIMAudioObject *audio = (HEIMAudioObject *)msg.messageObject;
            HETWIMInfoModel *content = [HETWIMInfoModel new];
            content.content = audio.url;
            content.type = TWIM_AUDIO;
            content.seconds = audio.duration;
            entitiy.user_ask = [content mj_JSONString];
            return entitiy;
        }
            break;
            
        case HEIMMessageTypeImage:
        {
            
            HEIMImageObject *image = (HEIMImageObject *)msg.messageObject;
            
            NSMutableArray *arr = @[].mutableCopy;
            for (HEIMImageObject *item in image.imageArray) {
                [arr addObject:item.url.path];
            }
            
            HETWIMInfoModel *content = [HETWIMInfoModel new];
            content.content = [arr componentsJoinedByString:@","];
            content.type = TWIM_IMAGE;
            entitiy.user_ask = [content mj_JSONString];
            return entitiy;
        }
            break;
            
        case HEIMMessageTypeVideo:
        {
            HEIMVideoObject *video = (HEIMVideoObject *)msg.messageObject;
            HETWIMInfoModel *content = [HETWIMInfoModel new];
            content.content = video.url.path;
            content.type = TWIM_VIDEO;
            entitiy.user_ask = [content mj_JSONString];
            return entitiy;
        }
            break;
            
        default:
            break;
    }
    return nil;
}

- (void)sendQueueIMMassage {
   
    // 加入发送队列
    // 创建操作
    for (HEIMMessageModel *message in self.modelList) {
        NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
            DLog(@"sendddd  开始执行任务...")
            [self sendIMMessage:message completion:^(BOOL success) {
                if (success) {
                    message.deliveryState = HEIMMessageDeliveryStateDeliveried;
                    [self.modelList removeFirstObject];
                    [self.cacheIMDataList removeFirstObject];
                    [self saveIMInfoListWithToId:message.message.to];
                }else {
                    message.deliveryState = HEIMMessageDeliveryStateFailed;
                }
                
                if ([self.delegate respondsToSelector:@selector(sendMessageHandler:)]) {
                    [self.delegate sendMessageHandler:message];
                }
                dispatch_semaphore_signal(self.semaphore); //这里请求成功信号量 +1 为1
            }];
            dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER); //信号量减1，走到这里如果信号量为0，则不再执行下面的代码
        }];
        
        [_queue addOperation:op1];
    }
}

- (void)sendIMMessage:(HEIMMessageModel *)message completion:(void (^)(BOOL success))completion{
    
    switch (message.message.type) {
        case HEIMMessageTypeText:
        {
            HETWInfoEntity *info = [self returnIMEntity:message];
            [self emit:[info mj_JSONObject] completion:^(BOOL success) {
                completion(success);
            }];
        }
            break;
        case HEIMMessageTypeAudio:
        {
            HETWInfoEntity *info = [self returnIMEntity:message];
            NSURL *url = [NSURL fileURLWithPath:info.contentModel.content];
            
            [WOAFNetWorkingHandle batchUploadFileWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil filePaths: @[url] fileNames:nil mediaType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
                
            } success:^(id  _Nonnull responseObject) {
                HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];
                
                if (response.success) {
                    info.contentModel.content = response.data.kSrc;
                    info.user_ask = [info.contentModel mj_JSONString];
                    HEIMAudioObject *audio = (HEIMAudioObject *)message.message.messageObject;
                    audio.url = response.data.kSrc;
                    [self emit:[info mj_JSONObject] completion:^(BOOL success) {
                        completion(success);
                        // 上传语音成功后删除缓存语音文件
                        [[HEAudioRecordManage sharedManager] removeFileAtPath:url.path];
                    }];
                }else {
                    completion(false);
                }
            } failure:^(NSError * _Nonnull error) {
                completion(false);
                return;
            }];
        }
            break;
            
        case HEIMMessageTypeImage:
        {
            HETWInfoEntity *info = [self returnIMEntity:message];
            
            NSMutableArray *arr = @[].mutableCopy;
            NSArray *urlPaths = [info.contentModel.content componentsSeparatedByString:@","];
            for (NSString *url in urlPaths) {
                [arr addObject:[NSURL fileURLWithPath:url]];
            }
            
            [WOAFNetWorkingHandle batchUploadFileWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil filePaths: arr fileNames:nil mediaType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
                
            } success:^(id  _Nonnull responseObject) {
                HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];
                
                if (response.success) {
                    info.contentModel.content = response.data.kSrc;
                    info.user_ask = [info.contentModel mj_JSONString];
                    [self emit:[info mj_JSONObject] completion:^(BOOL success) {
                        completion(success);
                    }];
                }else {
                    completion(false);
                }
            } failure:^(NSError * _Nonnull error) {
                completion(false);
                return;
            }];
        }
            break;
            
        case HEIMMessageTypeVideo:
        {
            HETWInfoEntity *info = [self returnIMEntity:message];
            NSURL *url = [NSURL fileURLWithPath:info.contentModel.content];
            
            [WOAFNetWorkingHandle batchUploadFileWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil filePaths: @[url] fileNames:nil mediaType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
                
            } success:^(id  _Nonnull responseObject) {
                HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];
                
                if (response.success) {
                    info.contentModel.content = response.data.kSrc;
                    info.user_ask = [info.contentModel mj_JSONString];
                    HEIMVideoObject *audio = (HEIMVideoObject *)message.message.messageObject;
                    audio.url = [NSURL URLWithString:response.data.kSrc];
                    [self emit:[info mj_JSONObject] completion:^(BOOL success) {
                        completion(success);
                        // 上传语音成功后删除缓存语音文件
//                        [[HEAudioRecordManage sharedManager] removeFileAtPath:url.path];
                    }];
                }else {
                    completion(false);
                }
            } failure:^(NSError * _Nonnull error) {
                completion(false);
                return;
            }];
        }
            break;
            
        default:
            completion(false);
            break;
    }
}

- (void)emit:(NSDictionary *)params completion:(void (^)(BOOL success))completion  {
    
    [[[HESocketManager sharedManager].socket emitWithAck:@"sendTwMsg" with: @[[params mj_JSONString]]] timingOutAfter:0 callback:^(NSArray * _Nonnull data) {
        DLog(@"sendddd  发送成功...%@",[params mj_JSONString] )

        NSDictionary *msgDict = (NSDictionary *)[data objectAtIndex:0];
        HEResponse *response = [HEResponse mj_objectWithKeyValues: msgDict];
        completion(response.success);
    }];
}

////添加监听 监听队列是否全部执行完毕
//[queue addObserver:self forKeyPath:@"operationCount" options:0 context:nil];
//-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//
//if ([keyPath isEqualToString:@"operationCount"]) {
//    NSOperationQueue *queue = (NSOperationQueue *)object;
//    if (queue.operationCount == 0) {
//        NSLog(@"全部完成");
//    }
//}
//}

#pragma mark - 资源文件上传
#pragma mark - 图片批量上传
- (void)batchUploadImageFile {
    
}

#pragma mark - HESocketManagerDelegate
- (void)onErrorHandler {
    dispatch_semaphore_signal(self.semaphore); //这里请求成功信号量 +1 为1
}

- (void)onDisConnectHandler {
    dispatch_semaphore_signal(self.semaphore); //这里请求成功信号量 +1 为1
}

 
#pragma mark -
- (NSMutableArray *)cacheIMDataList {
    if (!_cacheIMDataList) {
        _cacheIMDataList = [NSMutableArray array];
    }
    return _cacheIMDataList;
}

- (NSMutableArray<HEIMMessageModel *> *)modelList {
    if (!_modelList) {
        _modelList = [NSMutableArray array];
    }
    return _modelList;
}

- (void)dealloc {
    [[HESocketManager sharedManager] removeDelegate:self];
}

@end
